package com.hmdp.controller;


import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.service.IBlogService;
import com.hmdp.service.IUserService;
import com.hmdp.service.impl.BlogServiceImpl;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import net.bytebuddy.build.CachedReturnPlugin;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@RestController
@RequestMapping("/blog")
public class BlogController {

    @Resource
    private IBlogService blogService;
    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping
    public Result saveBlog(@RequestBody Blog blog) {

        return blogService.saveBlog(blog);
    }

    @PutMapping("/like/{id}")
    public Result likeBlog(@PathVariable("id") Long id) {
        // 修改点赞数量
//        blogService.update()
//                .setSql("liked = liked + 1").eq("id", id).update();
        //补充，当前用户可能没登录，你查点赞就会报错
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return Result.ok();
        }
        return blogService.likeBlog(id);
    }

    @GetMapping("/of/me")
    public Result queryMyBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .eq("user_id", user.getId()).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }

    @GetMapping("/of/user")
    public Result queryBlogByUserId(
            @RequestParam(value = "current", defaultValue = "1") Integer current,
            @RequestParam("id") Long id) {
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .eq("user_id", id).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }

    /**
     * 查询关注的人发布的文章,lastId是上一次查询中最小的文章时间戳s
     * @param max
     * @return
     */
    @GetMapping("/of/follow")
    public Result followBlog(@RequestParam("lastId") Long max,
                             @RequestParam(value = "offset", defaultValue = "0") Integer offset){
//        System.currentTimeMillis();
        return blogService.queryBlogOfFollow(max, offset);
    }

    @GetMapping("/hot")
    public Result queryHotBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();

        records.forEach(blog -> {
            //判断当前登录的用户是否点赞了当前博客，如果点赞了则将属性isLike设置为true
            //没登陆也得查询热门博客
            //1.获取当前登录的用户
            UserDTO user1 = UserHolder.getUser();
            if (user1 != null) {
                Long user_id = user1.getId();
                //2.判断是否点过赞
                String key = "blog:liked:" + blog.getId();
                Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, user_id.toString());

                if (BooleanUtil.isTrue(isMember)) {
                    blog.setIsLike(true);
                }
            }

            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
        });
        return Result.ok(records);
    }

    @GetMapping("/{id}")
    public Result Blogdetail(@PathVariable Long id) {
        Blog blog = blogService.blogDetail(id);
        if (blog == null) return Result.fail("博客不存在!");

        //判断当前用户是否点赞当前blog，如果是则将isLike属性设置为true，进行高亮
        //1.获取当前登录的用户
        Long userId = UserHolder.getUser().getId();
        //2.判断是否点过赞
        String key = "blog:liked:" + id;
        Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());

        if (BooleanUtil.isTrue(isMember)) {
            blog.setIsLike(true);
        }
        return Result.ok(blog);
    }

    @GetMapping("/likes/{id}")
    public Result getLikes(@PathVariable Long id) {
        Integer likes = blogService.getLikes(id);
        return Result.ok(likes);
    }
}
